package com.cspg.design.ui.search;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.cspg.design.CSPGApplication;
import com.cspg.design.R;
import com.cspg.design.adapter.Style;
import com.cspg.design.bean.UserInfo;
import com.cspg.design.bean.deviceBean.PointDeviceBean;
import com.cspg.design.bean.deviceBean.PolylineDeviceBean;
import com.cspg.design.bean.projectBean.ProjectBean;
import com.cspg.design.bean.shemeBean.MyHighVoltageSchemeBean;
import com.cspg.design.bean.shemeBean.MyLowVoltageSchemeBean;
import com.cspg.design.dao.gen.DaoSession;
import com.cspg.design.dao.gen.MyHighVoltageSchemeBeanDao;
import com.cspg.design.dao.gen.MyLowVoltageSchemeBeanDao;
import com.cspg.design.dao.gen.PointDeviceBeanDao;
import com.cspg.design.dao.gen.PolylineDeviceBeanDao;
import com.cspg.design.dao.gen.ProjectBeanDao;
import com.cspg.design.presenter.GTaskPresenter;
import com.cspg.design.ui.map.DesignMapActivity;
import com.cspg.design.ui.schemeActivity.MyHighVoltageSchemeEditActivity;
import com.cspg.design.ui.schemeActivity.MyLowVoltageSchemeEditActivity;
import com.cspg.design.utils.ActionBarUtil;
import com.cspg.design.utils.StatusBarUtil;
import com.cspg.design.utils.Utils;
import com.cspg.design.widget.AlertListDialog;
import com.cspg.design.widget.Loading;
import com.cspg.design.widget.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

public class SearchActivity extends AppCompatActivity {

    private ListView lvSearchResult;

    private DaoSession daoSession;

    private final ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();
    private SimpleAdapter adapter ;
    private final List<ProjectBean> projectBeanList = new ArrayList<>();

    private TextView noData ;

    private GTaskPresenter gTaskPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        StatusBarUtil.setStatusBarColor(this,R.color.colorPrimary);
        ActionBarUtil.setActionBar(this,R.string.search);

        daoSession = ((CSPGApplication)getApplication()).getDaoSession();
        lvSearchResult = findViewById(R.id.lv_search_result);
        noData = findViewById(R.id.tv_no_data);
        Intent intent = getIntent();
        int type = intent.getIntExtra("type",0);
        EditText searTxt = findViewById(R.id.et_search_txt);
        if (type == 1)
        {
            searTxt.setFocusable(true);
            searTxt.setFocusableInTouchMode(true);
            searTxt.requestFocus();
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }
        else
        {
            ActionBarUtil.setActionBar(this,R.string.home_design);
            search(type,searTxt.getText().toString());
        }
        searTxt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    //关闭软键盘
                    Utils.closeBoard(SearchActivity.this);
                    search(type,searTxt.getText().toString());
                    return true;
                }
                return false;
            }
        });
        adapter = new SimpleAdapter(SearchActivity.this, dataList, R.layout.listview_gtasks_project_item,
                new String[]{"title", "name", "status"},
                new int[]{R.id.item_gtasks_project_title, R.id.item_gtasks_project_name, R.id.item_gtasks_project_status}
        );
        lvSearchResult.setAdapter(adapter);
        lvSearchResult.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ProjectBean projectBean = projectBeanList.get(position);
                choiceScheme(position,projectBean);
            }
        });
        gTaskPresenter = new GTaskPresenter(this,lvSearchResult,projectBeanList,dataList,adapter);
    }

    private void search(int type,String txt)
    {
        if (type == 1)
        {
            daoSession.getProjectBeanDao().queryBuilder()
                    .where(ProjectBeanDao.Properties.ProjectName.like("%"+txt+"%"))
                    .rx().list().observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<List<ProjectBean>>() {
                        @Override
                        public void call(List<ProjectBean> projectBeans) {
                            if (projectBeans.size() == 0)
                            {
                                noData.setVisibility(View.VISIBLE);
                            }
                            else
                            {
                                noData.setVisibility(View.GONE);
                            }
                            projectBeanList.clear();
                            for (int i = 0; i < projectBeans.size(); i++) {
                                if (UserInfo.getInstance().role.contains("设计"))
                                {
                                    if (projectBeans.get(i).getProjectStatus().equals("done")) {
                                        projectBeanList.add(projectBeans.get(i));
                                    }
                                }else {
                                    if (projectBeans.get(i).getProjectStatus().equals("doing")) {
                                        projectBeanList.add(projectBeans.get(i));
                                    }
                                }
                            }
                            refreshListView();
                        }
                    });
        }
        else if (type == 2)
        {
            daoSession.getProjectBeanDao().queryBuilder()
                    .where(ProjectBeanDao.Properties.ProjectName.like("%"+txt+"%"))
                    .rx().list().observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<List<ProjectBean>>() {
                        @Override
                        public void call(List<ProjectBean> projectBeans) {
                            if (projectBeans.size() == 0)
                            {
                                noData.setVisibility(View.VISIBLE);
                            }
                            else
                            {
                                noData.setVisibility(View.GONE);
                            }
                            projectBeanList.clear();
                            for (int i = 0; i < projectBeans.size(); i++) {
                                if (UserInfo.getInstance().role.contains("设计"))
                                {
                                    if (projectBeans.get(i).getProjectStatus().equals("done")) {
                                        projectBeanList.add(projectBeans.get(i));
                                    }
                                }else {
                                    if (projectBeans.get(i).getProjectStatus().equals("did") || projectBeans.get(i).getProjectStatus().equals("done")) {
                                        projectBeanList.add(projectBeans.get(i));
                                    }
                                }
                            }
                            refreshListView();
                        }
                    });
        }
    }

    private void refreshListView()
    {

        dataList.clear();
        for (int i = 0; i < projectBeanList.size(); i++) {
            HashMap<String, String> hashMap = new HashMap<String, String>();
            hashMap.put("title", projectBeanList.get(i).getProjectTitle());
            hashMap.put("name", projectBeanList.get(i).getProjectName());
            switch (projectBeanList.get(i).getProjectStatus())
            {
                case "doing":
                    hashMap.put("status", "设计中");
                    break;
                case "did":
                    hashMap.put("status", "完成");
                    break;
                case "done":
                    hashMap.put("status", "已上传");
                    break;
                case "checked":
                    hashMap.put("status", "送评审");
                    break;
            }
            dataList.add(hashMap);
        }
        adapter.notifyDataSetChanged();
    }

    //方案选择对话框
    private void choiceScheme(int position,ProjectBean projectBean)
    {

        if (UserInfo.getInstance().role.contains("设计"))
        {
            String schemeName = projectBean.getSchemeName();
            new AlertListDialog.ListBuilder(SearchActivity.this)
                    .setDividerColorRes(R.color.color_divider)
                    .setDividerHeightRes(R.dimen.dp1)
                    .setTitle("请操作")
                    .setIcon(R.drawable.ic_info)
                    .setItems(new String[]{"成果查看","方案查看", "设计意见"}, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            switch (which)
                            {
                                case 0:
                                    //跳转到地图
                                    Intent intent = new Intent(SearchActivity.this, DesignMapActivity.class);
                                    intent.putExtra("projectId", projectBean.getProjectId());
                                    intent.putExtra("schemeName",schemeName);
                                    startActivity(intent);
                                    break;
                                case 1:
                                    goToScheme(projectBean);
                                    break;
                                case 2:
                                    EditText editText = new EditText(SearchActivity.this);
                                    editText.setGravity(Gravity.TOP);
                                    editText.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
                                    editText.setMinHeight(40);
                                    editText.setMinLines(10);
                                    editText.setPadding(20,15,20,15);
                                    editText.setFocusable(true);
                                    editText.setFocusableInTouchMode(true);
                                    editText.requestFocus();
                                    SearchActivity.this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
                                    new AlertDialog.Builder(SearchActivity.this)
                                            .setTitle("请输入意见")
                                            .setIcon(R.drawable.ic_info)
                                            .setView(editText)
                                            .setNeutralButton("不通过", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            hideSoftInput(editText);
                                                        }
                                                    });
                                                    String advise = editText.getText().toString();
                                                    if (advise.trim().isEmpty())
                                                    {
                                                        ToastUtils.toast(SearchActivity.this,"成果提交失败，意见不能为空。。。。");
                                                        return;
                                                    }
                                                    System.out.println(advise);
                                                    projectBean.setRemark(advise);
                                                    projectBean.setProjectStatus("doing");
                                                    updateProjectStatus(position,projectBean,"doing");
                                                }
                                            })
                                            .setPositiveButton("通过", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    String advise = editText.getText().toString();
                                                    System.out.println(advise);
                                                    projectBean.setRemark(advise);
                                                    projectBean.setProjectStatus("checked");
                                                    submitAndUpdateProject(position,projectBean,"checked");
                                                }
                                            })
                                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            hideSoftInput(editText);
                                                        }
                                                    });
                                                    dialog.dismiss();
                                                }
                                            })
                                            .create().show();
                                    break;
                            }
                        }
                    }).setNeutralButton("取消", (dialog, which) -> dialog.dismiss())
                    .create().show();
        }else {

            if (projectBean.getProjectStatus().equals("doing")) {
                String schemeName = projectBean.getSchemeName();
                if (schemeName == null || schemeName.trim().isEmpty()) {
                    //显示方案选择
                    new AlertListDialog.ListBuilder(SearchActivity.this)
                            .setDividerColorRes(R.color.color_divider)
                            .setDividerHeightRes(R.dimen.dp1)
                            .setTitle("选择方案")
                            .setIcon(R.drawable.ic_info)
                            .setItems(new String[]{"架空方案", "低压方案"}, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    switch (which) {
                                        case 0:
                                            daoSession.getMyHighVoltageSchemeBeanDao()
                                                    .queryBuilder().rx().list()
                                                    .observeOn(AndroidSchedulers.mainThread())
                                                    .subscribe(new Action1<List<MyHighVoltageSchemeBean>>() {
                                                        @Override
                                                        public void call(List<MyHighVoltageSchemeBean> myHighVoltageSchemeBeans) {
                                                            if (myHighVoltageSchemeBeans.size() == 0) {
                                                                Toast.makeText(SearchActivity.this, "无方案数据，请到方案设置中添加方案", Toast.LENGTH_LONG).show();
                                                                return;
                                                            }
                                                            String[] schemeNames = new String[myHighVoltageSchemeBeans.size()];
                                                            for (int i = 0; i < schemeNames.length; i++) {
                                                                schemeNames[i] = myHighVoltageSchemeBeans.get(i).getSchemeName();
                                                            }
                                                            new AlertListDialog.ListBuilder(SearchActivity.this)
                                                                    .setDividerColorRes(R.color.color_divider)
                                                                    .setDividerHeightRes(R.dimen.dp1)
                                                                    .setTitle("架空方案")
                                                                    .setIcon(R.drawable.ic_info)
                                                                    .setItems(schemeNames, new DialogInterface.OnClickListener() {
                                                                        @Override
                                                                        public void onClick(DialogInterface dialog, int which) {
                                                                            dialog.dismiss();
                                                                            Loading.getIns().target(SearchActivity.this).show(Style.LOADING);
                                                                            saveScheme(position, projectBean, myHighVoltageSchemeBeans.get(which).getSchemeName(), "high");
                                                                        }
                                                                    }).create().show();
                                                        }
                                                    });
                                            break;
                                        case 1:
                                            daoSession.getMyLowVoltageSchemeBeanDao()
                                                    .queryBuilder().rx().list()
                                                    .observeOn(AndroidSchedulers.mainThread())
                                                    .subscribe(new Action1<List<MyLowVoltageSchemeBean>>() {
                                                        @Override
                                                        public void call(List<MyLowVoltageSchemeBean> myLowVoltageSchemeBeans) {
                                                            if (myLowVoltageSchemeBeans.size() == 0) {
                                                                Toast.makeText(SearchActivity.this, "无方案数据，请到方案设置中添加方案", Toast.LENGTH_LONG).show();
                                                                return;
                                                            }
                                                            String[] schemeNames = new String[myLowVoltageSchemeBeans.size()];
                                                            for (int i = 0; i < schemeNames.length; i++) {
                                                                schemeNames[i] = myLowVoltageSchemeBeans.get(i).getSchemeName();
                                                            }
                                                            new AlertListDialog.ListBuilder(SearchActivity.this)
                                                                    .setDividerColorRes(R.color.color_divider)
                                                                    .setDividerHeightRes(R.dimen.dp1)
                                                                    .setTitle("低压方案")
                                                                    .setIcon(R.drawable.ic_info)
                                                                    .setItems(schemeNames, new DialogInterface.OnClickListener() {
                                                                        @Override
                                                                        public void onClick(DialogInterface dialog, int which) {
                                                                            dialog.dismiss();
                                                                            Loading.getIns().target(SearchActivity.this).show(Style.LOADING);
                                                                            saveScheme(position, projectBean, myLowVoltageSchemeBeans.get(which).getSchemeName(), "low");
                                                                        }
                                                                    }).create().show();
                                                        }
                                                    });
                                            break;
                                    }
                                }
                            })
                            .create().show();
                } else {
                    new AlertListDialog.ListBuilder(SearchActivity.this)
                            .setDividerColorRes(R.color.color_divider)
                            .setDividerHeightRes(R.dimen.dp1)
                            .setTitle("选择方案")
                            .setIcon(R.drawable.ic_info)
                            .setItems(new String[]{"完成", "进行设计", "上传", "修改方案", "清空设计数据"
                            }, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    switch (which) {
                                        case 0:
                                            Loading.getIns().target(SearchActivity.this).show(Style.LOADING);
                                            Log.e(SearchActivity.class.getName(), "修改数据状态为完成");
                                            updateProjectStatus(position, projectBean, "did");
                                            break;
                                        case 1:
                                            //跳转到地图
                                            Intent intent = new Intent(SearchActivity.this, DesignMapActivity.class);
                                            intent.putExtra("projectId", projectBean.getProjectId());
                                            intent.putExtra("schemeName", schemeName);
                                            startActivity(intent);
                                            break;
                                        case 2:
                                            //进行上传;
                                            Loading.getIns().target(SearchActivity.this).show(Style.LOADING);
                                            Log.e(SearchActivity.class.getName(), "修改数据状态为已经上传");
                                            updateProjectStatus(position, projectBean, "done");
                                            break;
                                        case 3:
                                            //修改方案名称;
                                            projectBean.setSchemeName(null);
                                            choiceScheme(position, projectBean);
                                            break;
                                        case 4:
                                            //清空设计数据数据;
                                            deleteDesignData(projectBean.getProjectId());
                                            break;
                                    }
                                }
                            }).create().show();
                }
            } else if (projectBean.getProjectStatus().equals("did")) {
                new AlertListDialog.ListBuilder(SearchActivity.this)
                        .setDividerColorRes(R.color.color_divider)
                        .setDividerHeightRes(R.dimen.dp1)
                        .setTitle("请操作")
                        .setNegativeButton("取消", (dialog, which) -> dialog.dismiss())
                        .setIcon(R.drawable.ic_info)
                        .setItems(new String[]{"上传", "再次进行设计"}, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which) {
                                    case 0:
                                        //进行上传
                                        Log.e(SearchActivity.class.getName(), "修改数据状态为已经上传");
                                        updateProjectStatus(position, projectBean, "done");
                                        uploadDeviceData(projectBean);
                                        break;
                                    case 1:
                                        Log.e(SearchActivity.class.getName(), "修改数据状态为设计");
                                        updateProjectStatus(position, projectBean, "doing");
//                                    uploadDeviceData(projectBean);
                                        break;
                                }
                            }
                        }).create().show();
            } else if (projectBean.getProjectStatus().equals("checked")) {
                new AlertListDialog.ListBuilder(SearchActivity.this)
                        .setDividerColorRes(R.color.color_divider)
                        .setDividerHeightRes(R.dimen.dp1)
                        .setTitle("请操作")
                        .setNegativeButton("取消", (dialog, which) -> dialog.dismiss())
                        .setIcon(R.drawable.ic_info)
                        .setItems(new String[]{"项目流程"}, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch (which) {
                                    case 0:
                                        //进行上传
                                        Log.e(SearchActivity.class.getName(), "修改数据状态为已经上传");
                                        updateProjectStatus(position, projectBean, "done");
                                        uploadDeviceData(projectBean);
                                        break;
                                }
                            }
                        }).create().show();
            }
        }

    }
    //更新项目中的方案名称
    private void saveScheme(int index, ProjectBean projectBean, String schemeName, String schemeType) {
        gTaskPresenter.updateProject(projectBean,2,index);
    }
    // 上传数据
    private void uploadDeviceData(ProjectBean projectBean)
    {
        String projectId = projectBean.getProjectId();
        List<PointDeviceBean> pointDeviceBeanList = daoSession.getPointDeviceBeanDao().queryBuilder()
                .where(PointDeviceBeanDao.Properties.ProjectId.eq(projectId)).list();
        List<PolylineDeviceBean> polylineDeviceBeanList = daoSession.getPolylineDeviceBeanDao().queryBuilder()
                .where(PolylineDeviceBeanDao.Properties.ProjectId.eq(projectId)).list();
        gTaskPresenter.uploadPoints(pointDeviceBeanList);
        gTaskPresenter.uploadPolylines(polylineDeviceBeanList);
    }

    //修改项目状态为完成
    private void updateProjectStatus(int index, ProjectBean projectBean, String status) {
        projectBean.setProjectStatus(status);
        gTaskPresenter.updateProject(projectBean,1,index);
        daoSession.getProjectBeanDao().rx().save(projectBean).observeOn(AndroidSchedulers.mainThread()).subscribe(pb -> {
                   if(status.equals("doing"))
                   {
                       projectBeanList.remove(index);
                   }
                   refreshListView();
                   Toast.makeText(SearchActivity.this, "项目状态已经更新", Toast.LENGTH_LONG).show();
                }
        );
    }
    //清空设计数据
    private void deleteDesignData(String projectId)
    {
        List<PointDeviceBean> pointDeviceBeanList =  daoSession.getPointDeviceBeanDao().queryBuilder().where(PointDeviceBeanDao.Properties.ProjectId.eq(projectId)).list();
        daoSession.getPointDeviceBeanDao().rx()
                .deleteInTx(pointDeviceBeanList.toArray(new PointDeviceBean[pointDeviceBeanList.size()]))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {}
                });
        List<PolylineDeviceBean> polylineDeviceBeanList =  daoSession.getPolylineDeviceBeanDao().queryBuilder().where(PolylineDeviceBeanDao.Properties.ProjectId.eq(projectId)).list();
        daoSession.getPolylineDeviceBeanDao().rx()
                .deleteInTx(polylineDeviceBeanList.toArray(new PolylineDeviceBean[polylineDeviceBeanList.size()]))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(SearchActivity.this, "设计数据删除完成", Toast.LENGTH_LONG).show();
                            }
                        }, 2000);
                    }
                });
    }

    private void  hideSoftInput(EditText editText){
        InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(editText.getWindowToken(),  InputMethodManager.HIDE_NOT_ALWAYS);
    }

    private void goToScheme(ProjectBean projectBean)
    {
        if (projectBean == null)
        {
            ToastUtils.toast(SearchActivity.this,"项目信息为空,无法查看....");
        }
        String schemeName = projectBean.getSchemeName();
        switch (projectBean.getSchemaType())
        {
            case "high":
                MyHighVoltageSchemeBean myHighVoltageSchemeBean = daoSession
                        .getMyHighVoltageSchemeBeanDao()
                        .queryBuilder()
                        .where(MyHighVoltageSchemeBeanDao.Properties.SchemeName.eq(schemeName),
                                MyHighVoltageSchemeBeanDao.Properties.UserName.eq(projectBean.getUserName()))
                        .unique();
                Intent intent = new Intent(SearchActivity.this, MyHighVoltageSchemeEditActivity.class);
                intent.putExtra("code", "1");
                intent.putExtra("bean", myHighVoltageSchemeBean);
                startActivity(intent);
                break;
            case "low":
                MyLowVoltageSchemeBean myLowVoltageSchemeBean = daoSession.getMyLowVoltageSchemeBeanDao()
                        .queryBuilder()
                        .where(MyLowVoltageSchemeBeanDao.Properties.SchemeName.eq(schemeName),
                                MyLowVoltageSchemeBeanDao.Properties.UserName.eq(projectBean.getUserName()))
                        .unique();
                Intent intent1 = new Intent(SearchActivity.this, MyLowVoltageSchemeEditActivity.class);
                intent1.putExtra("code", "1");
                intent1.putExtra("bean", myLowVoltageSchemeBean);
                startActivity(intent1);
                break;
        }
    }

    //进行项目提交到评审平台后再更新项目状态
    private void submitAndUpdateProject(int index, ProjectBean projectBean, String status)
    {
        projectBean.setProjectStatus(status);
        gTaskPresenter.submitToReview(projectBean,1,index);
    }

}